package com.lei.library_mvp_retrofit.http.token;

import com.blankj.utilcode.util.SPUtils;
import com.lei.library_mvp_retrofit.http.api.Api;
import com.lei.library_mvp_retrofit.http.factroy.BaseRetrofitFactroy;
import com.lei.library_mvp_retrofit.http.url.BaseUrl;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ProjectName : YoHoJava_002
 * @Author : 雷金泷
 * @Time : 2021/1/8 16:12
 * @Description : 文件描述
 */
public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response;
        if (SPUtils.getInstance().contains(BaseUrl.TOKEN_KEY)){
            response = chain.proceed(addToken(request,BaseUrl.TOKEN_KEY));
        }else {
            response = chain.proceed(request);
        }
        if (response.code() == BaseUrl.TOKEN_NON){
            String newToken = createToken();
            SPUtils.getInstance().put(BaseUrl.TOKEN_KEY,newToken);
            response = chain.proceed(addToken(request,newToken));
        }
        return response;
    }

    private String createToken() throws IOException {
        return Objects
                .requireNonNull(BaseRetrofitFactroy
                        .create(Api.class)
                        .token("password","","")
                        .execute()
                        .body())
                .access_token;
    }

    private Request addToken(Request request, String token) {
        return request.newBuilder().addHeader("",""+token).build();
    }
}
